package com.lishe.lishe.lishe.ImageSelector;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.utils.ImageUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by shino on 2017/10/19.
 * 图片选择器
 */

public class ImageSelectorActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout callBack;
    private GridView grideview;
    private TextView allPictrue;
    private TextView confirm;
    private TextView preview;
    private ImageAdapter adapter;
    private FloderAdapter floderAdapter;
    private LinkedList<ImageObject> selectImage = new LinkedList<>();//被选中的图片
    private LinkedList<ImageObject> floders = new LinkedList<>();
    private LinkedList<ImageObject> showImages = new LinkedList<>();
    private Map<String, List<ImageObject>> imageMap = new HashMap<>();
    private ImageUtils imageUtils;
    private int maxCount = 0;

    public static void jump(Activity activity, int requscode, int maxCount) {
        Intent intent = new Intent(activity, ImageSelectorActivity.class);
        intent.putExtra("maxCount", maxCount);
        activity.startActivityForResult(intent, requscode);
    }

    public static void jump(Fragment fragment, int requscode, int maxCount) {
        Intent intent = new Intent(fragment.getActivity(), ImageSelectorActivity.class);
        intent.putExtra("maxCount", maxCount);
        fragment.startActivityForResult(intent, requscode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imge_selector);
        maxCount = getIntent().getIntExtra("maxCount", 0);
        imageUtils = new ImageUtils(this);
        adapter = new ImageAdapter(ImageSelectorActivity.this, showImages);
        floderAdapter = new FloderAdapter(ImageSelectorActivity.this, floders);
        initView();
        getImage();
    }


    private void initView() {
        callBack = findViewById(R.id.callBack);
        grideview = findViewById(R.id.grideview);
        allPictrue = findViewById(R.id.allPictrue);
        confirm = findViewById(R.id.confirm);
        confirm.setText("完成");
        preview = findViewById(R.id.preview);
        preview.setVisibility(View.GONE);
        grideview.setAdapter(adapter);
        grideview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("grideview", showImages.get(i).getPath());
                ImageObject imageObject = showImages.get(i);
                if (!imageObject.isCheck() && selectImage.size() == maxCount) {
                    toast("不能选中超过" + maxCount + "张图！");
                    return;
                }
                if (imageObject.isCheck()) {//取消选中
                    imageObject.setCheck(false);
                } else {//选中
                    imageObject.setCheck(true);
                }
                selecedImage(imageObject);
                adapter.notifyDataSetChanged();
            }
        });
        preview.setOnClickListener(this);
        confirm.setOnClickListener(this);
        allPictrue.setOnClickListener(this);
        callBack.setOnClickListener(this);
    }

    /**
     * 获取系统相册下所有图片路径
     */
    private void getImage() {
        if (PermissionUtils.isStorageWritePermission(ImageSelectorActivity.this)) {
            ImageScanner.scanImage(new ImageScanner.OnScanListener() {
                @Override
                public void onScanCompleted(Map<String, List<ImageObject>> imageMap) {
                    selectImage.clear();
                    ImageSelectorActivity.this.imageMap = imageMap;
                    doImage(imageMap);
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 对图片进行分类显示
     *
     * @param imageMap 图片文件夹
     */
    private void doImage(Map<String, List<ImageObject>> imageMap) {
        floders.clear();
        showImages.clear();
        List<String> flodernames = new ArrayList<>(imageMap.keySet());//获得所有key值（文件夹名称）
        for (int i = 0; i < flodernames.size(); i++) {
            if (i == 0) {
                showImages.addAll(imageMap.get(flodernames.get(i)));
            }

            ImageObject imageObject = new ImageObject();
            imageObject.setName(flodernames.get(i));
            imageObject.setPath(imageMap.get(flodernames.get(i)).get(0).getPath());//取第一个文件夹的第0个图的路径
            imageObject.setCheck(false);
            imageObject.setImageSize(imageMap.get(flodernames.get(i)).size());
            floders.add(imageObject);
        }
        adapter.notifyDataSetChanged();
        floderAdapter.notifyDataSetChanged();
    }

    /**
     * 过滤被选中或去除选中图片
     *
     * @param imageObject
     */
    private void selecedImage(ImageObject imageObject) {
        if (!imageObject.isCheck()) {//取消
//            for (int i = 0; i < selectImage.size(); i++) {
//                if (selectImage.get(i).getPath().equals(imageObject.getPath())) {
//                    selectImage.remove(imageObject);
//                    return;
//                }
//            }
            for (ImageObject imageObject1 : selectImage) {
                if (imageObject1.getPath().equals(imageObject.getPath())) {
                    selectImage.remove(imageObject);
                    break;
                }
            }
        } else {
            selectImage.add(imageObject);
        }
        if (maxCount > 0) {
            if (selectImage.size() > 0) {
                confirm.setText("完成(" + selectImage.size() + "/" + maxCount + ")");
            } else {
                confirm.setText("完成");
            }
        }
    }

    PopupWindow floderPop;

    private int index = -1;

    private void createFloaderPop() {
        if (floderPop == null) {
            View floderLayout = getLayoutInflater().inflate(R.layout.item_selected_image_floder, null);
            ListView listView = floderLayout.findViewById(R.id.listView);
            floderPop = new PopupWindow(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (index != -1) {
                        floders.get(index).setCheck(false);
                    }
                    index = i;
                    floders.get(i).setCheck(!floders.get(i).isCheck());
                    allPictrue.setText(floders.get(i).getName());
                    showImages.clear();
                    Log.e("key", floders.get(i).getName());
                    showImages.addAll(imageMap.get(floders.get(i).getName()));
                    adapter.notifyDataSetChanged();
                    floderPop.dismiss();
                }
            });
            listView.setAdapter(floderAdapter);
            floderPop.setBackgroundDrawable(new BitmapDrawable());//去掉间隔
            floderPop.setContentView(floderLayout);
            floderPop.setOutsideTouchable(true);
            floderPop.showAtLocation(allPictrue, Gravity.TOP, 0, 0);
        } else {
            floderPop.showAtLocation(allPictrue, Gravity.TOP, 0, 0);
            floderAdapter.notifyDataSetChanged();
        }

    }

    /**
     * SD卡权限处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ImageScanner.scanImage(new ImageScanner.OnScanListener() {
                        @Override
                        public void onScanCompleted(Map<String, List<ImageObject>> imageMap) {
                            selectImage.clear();
                            ImageSelectorActivity.this.imageMap = imageMap;
                            doImage(imageMap);
                            adapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    // permission denied
                    // request failed
                }
                return;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.callBack://返回
                finish();
                break;
            case R.id.preview://预览

                break;
            case R.id.confirm://完成
                if (selectImage.size() == 0) {
                    toast("请选择相片！");
                    return;
                }
                Intent itent = new Intent();
                itent.putExtra("data", selectImage);
                setResult(RESULT_OK, itent);
                finish();
                break;
            case R.id.allPictrue://所有图片
                Log.e("所有图片", "allPictrue");
                createFloaderPop();
                break;
        }
    }
}
